package cn.sjxy.regi.service.impl;

import cn.sjxy.regi.exception.CustomException;
import cn.sjxy.regi.mapper.CategoryMapper;
import cn.sjxy.regi.pojo.Category;
import cn.sjxy.regi.pojo.Dish;
import cn.sjxy.regi.pojo.Setmeal;
import cn.sjxy.regi.service.CategoryService;
import cn.sjxy.regi.service.DishService;
import cn.sjxy.regi.service.SetmealService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * ClassName:CategoryServiceImpl
 * Package:cn.sjxy.regi.service.impl
 * Description:
 *
 * @Date:2022/5/27 19:57
 * @Author:SXW
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    // 懒加载解决循环依赖
    @Lazy
    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 根据id删除，删除之前需要进行判断
     * 1. 查询是否关联菜品，关联则抛出业务异常
     * 2. 是否关联套餐，同上
     * 3. 正常删除
     *
     * @param id
     */
    @Override
    public void remove(Long id) {
        /* 1. 查询是否关联菜品 */
        LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper();
        dishWrapper.eq(Dish::getCategoryId, id);
        int dishCount = dishService.count(dishWrapper);
        if (dishCount > 0) {
            // count > 0 说明关联了菜品，不能删除，抛出异常
            throw new CustomException("关联了菜品，无法删除");
        }
        /* 2. 查询是否关联套餐 */
        LambdaQueryWrapper<Setmeal> setmealWrapper = new LambdaQueryWrapper();
        setmealWrapper.eq(Setmeal::getCategoryId, id);
        int setmealCount = setmealService.count(setmealWrapper);

        if (setmealCount > 0) {
            // 抛出异常
            throw new CustomException("关联了套餐，无法删除");

        }
        /* 3. 正常删除 */
        super.removeById(id);
    }

    @Override
    public Page getPage(int page, int pageSize) {
        // 分页构造器
        Page<Category> pageInfo = new Page(page, pageSize);
        // 条件构造器，设置排序条件
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper();
        wrapper.orderByAsc(Category::getSort);
        this.page(pageInfo, wrapper);
        return pageInfo;
    }

    @Override
    public List<Category> getCategorys(Category category) {
        // 条件构造器
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper();
        // 添加条件
        wrapper.eq(category.getType() != null, Category::getType, category.getType());
        // 排序条件
        wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = this.list(wrapper);
        return list;
    }
}
